﻿using D.WebApi.Core.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace D.WebApi.Core.Filters
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class ExtExceptionFilterAttbute : Attribute, IExceptionFilter
    {

        private readonly ILogger _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="loggerFactory"></param>
        public ExtExceptionFilterAttbute(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ExtExceptionFilterAttbute>();
        }

        public void OnException(ExceptionContext context)
        {
            // 未经处理的异常
            if (!context.ExceptionHandled)
            {
                _logger.LogCritical(context.Exception, context.ActionDescriptor.DisplayName);
                var content = JsonSerializer.Serialize(new ApiResult()
                {
                    Succes = SuccessTypeEnum.Error,
                    ErrorMsg = "系统异常"
                });

                context.Result = new ContentResult
                {
                    Content = content,
                    StatusCode = 500,
                    ContentType = "application/json; charset=utf-8"
                };

                context.ExceptionHandled = true;
            }
            else
            {
                _logger.LogError(context.Exception, context.ActionDescriptor.DisplayName);
            }

        }
    }
}
